﻿using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Topro.Watchman
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        public MainForm()
        {
            InitializeComponent();

            //样式
            dgIQS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;//列宽不自动调整,手工添加列
            //dgGateWay.RowHeadersWidth = 12;//行标题宽度固定12
            dgIQS.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//不能用鼠标调整列标头宽度
            //dgGateWay.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;//奇数行背景色
            dgIQS.BackgroundColor = Color.White;//控件背景色
            dgIQS.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
            dgIQS.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容居中显示
            //行为
            dgIQS.AutoGenerateColumns = false;//不自动创建列
            dgIQS.AllowUserToAddRows = false;//不启用添加
            dgIQS.ReadOnly = true;//不启用编辑
            dgIQS.AllowUserToDeleteRows = false;//不启用删除
            dgIQS.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//单击单元格选中整行
            dgIQS.MultiSelect = false;//不能多选
            dgIQS.AllowUserToResizeRows = false;//禁止用户改变DataGridView1の所有行的行高
            dgIQS.RowTemplate.Height = 30;//设置行高
            //dgGateWay.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//自动填充
            dgIQS.RowHeadersVisible = false;

            //BindingSource bs = new BindingSource();
            //bs.DataSource = EnumUtil.ToDictionary(typeof(StockStatus));

            //cbbCommandStatus.DataSource = bs;
            //cbbCommandStatus.ValueMember = "key";
            //cbbCommandStatus.DisplayMember = "value";
            //cbbCommandStatus.SelectedIndex = 1;
        }

        #region 搜索
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var containerCode = txtContainerCode.Text.Trim();

            this.Query();

            //员工编号:
            var watchmanBy = txtWatchmanBy.Text.Trim();
            //机台号
            string watchmanMachineCode = ConfigurationManager.AppSettings["MachineCode"].Trim();

            if (string.IsNullOrEmpty(watchmanBy))
            {
                MessageBox.Show("员工号不能为空.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var watchmanByReg = new Regex(@"^28(\d+)$");
            if (!watchmanByReg.IsMatch(watchmanBy))
            {
                MessageBox.Show("员工号必须以28开头且7位数字组成.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            watchmanByReg = new Regex(@"^[0-9]{7}$");
            if (!watchmanByReg.IsMatch(watchmanBy))
            {
                MessageBox.Show("员工号必须以28开头且7位数字组成.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(containerCode))
            {
                MessageBox.Show("容器编码不能为空.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            using (IDbConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
            {
                //查询Sql
                var iqsQuerySql = "select Id,LotBatch,PartNum,HeapNumber,PanelQuan,StaffNum,PressProgramFull from iqs WHERE ContainerCode=@ContainerCode AND WatchmanStatus=0";
                //查询
                var iqs = conn.Query<IQS>(iqsQuerySql, new { ContainerCode = containerCode }).FirstOrDefault();

                if(iqs == null)
                {
                    MessageBox.Show("查无此容器编码.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //查询Sql
                var iqsUpdateSql = "update IQS Set WatchmanMachineCode=@WatchmanMachineCode,WatchmanDate=@WatchmanDate,WatchmanBy=@WatchmanBy,WatchmanStatus=1 WHERE Id=@Id";
                //执行
                var status = (int)conn.Execute(iqsUpdateSql, new { WatchmanMachineCode = watchmanMachineCode, WatchmanDate = DateTime.Now, WatchmanBy = watchmanBy, Id = iqs.Id });
                if (status <= 0)
                {
                    throw new Exception("更新状态失败.");
                }

                txtLotBatch.Text = iqs.LotBatch;
                txtPartNum.Text = iqs.PartNum;
                txtHeapNumber.Text = iqs.HeapNumber;
                txtPressProgram.Text = iqs.PressProgramFull;
                txtContainerCode.Text = "";
            }
        }
        #endregion

        /// <summary>
        /// 查询
        /// </summary>
        public void Query()
        {
            //机台号
            string machineCode = ConfigurationManager.AppSettings["MachineCode"].Trim();

            if (!string.IsNullOrEmpty(machineCode))
            {
                using (IDbConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
                {
                    //查询Sql
                    var iqsQuerySql = "select Id,LotBatch,PartNum,HeapNumber,PanelQuan,StaffNum,PressProgramFull,WatchmanBy from iqs where WatchmanMachineCode=@WatchmanMachineCode ORDER BY Id DESC LIMIT 0,10;";
                    //查询
                    var list = conn.Query<IQS>(iqsQuerySql,new { WatchmanMachineCode = machineCode }).ToList();
                    //绑定数据
                    this.dgIQS.DataSource = new BindingList<IQS>(list);
                }
            }
        }
    }
}
